var babel = require('rollup-plugin-babel');
var { nodeResolve } = require('@rollup/plugin-node-resolve');
var commonjs = require('@rollup/plugin-commonjs');
var { terser } = require('rollup-plugin-terser');
var alias = require('@rollup/plugin-alias');
const path = require('path');
const fs = require('fs');
var less = require('rollup-plugin-less');
const { env } = require('process');

// 获取模板下的所有页面入口文件
function getPageEntries(template) {
  const entries = [];
  const pageDir = path.resolve(__dirname, `../src/theme/${template}/lib/page`);

  // 检查是否存在lib/page目录结构
  if (fs.existsSync(pageDir)) {
    const pageFolders = fs.readdirSync(pageDir);

    pageFolders.forEach((pageFolder) => {
      const pagePath = path.join(pageDir, pageFolder);
      const indexFile = path.join(pagePath, 'index.js');

      if (fs.statSync(pagePath).isDirectory() && fs.existsSync(indexFile)) {
        entries.push({
          name: pageFolder,
          path: indexFile,
          output: `src/theme/${template}/assets/${pageFolder}.js`,
        });
      }
    });
  }

  return entries;
}

// 生成别名配置
function generateAliases(template) {
  const basePath = path.resolve(__dirname, `../src/theme/${template}/lib`);
  const aliases = [
    { find: '@', replacement: basePath },
    { find: '@template', replacement: path.resolve(__dirname, `../src/theme/${template}`) },
  ];

  // 根据实际存在的目录添加别名
  if (fs.existsSync(path.join(basePath, 'api'))) {
    aliases.push({ find: '@api', replacement: path.join(basePath, 'api') });
  }
  if (fs.existsSync(path.join(basePath, 'component'))) {
    aliases.push({ find: '@components', replacement: path.join(basePath, 'component') });
  }
  if (fs.existsSync(path.join(basePath, 'js'))) {
    aliases.push({ find: '@js', replacement: path.join(basePath, 'js') });
  }
  if (fs.existsSync(path.join(basePath, 'style'))) {
    aliases.push({ find: '@style', replacement: path.join(basePath, 'style') });
  }

  return aliases;
}

// 获取组件入口文件
function getComponentEntries(template) {
  const entries = [];
  const libPath = path.resolve(__dirname, `../src/theme/${template}/lib`);

  if (!fs.existsSync(libPath)) return entries;

  // 检查现代组件结构
  const componentPath = path.join(libPath, 'component', 'index.js');
  if (fs.existsSync(componentPath)) {
    entries.push({
      name: 'component',
      path: componentPath,
      output: `src/theme/${template}/assets/component.js`,
    });
  }

  // 检查传统JS结构
  const appJsPath = path.join(libPath, 'js', 'app.js');
  if (fs.existsSync(appJsPath)) {
    entries.push({
      name: 'app',
      path: appJsPath,
      output: `src/theme/${template}/assets/${template}_app.js`,
    });
  }

  return entries;
}

// 生成动态配置
function generateConfig() {
  const templates = [env.NODE_THEME]; //getTemplates();env.NODE_THEME
  const configs = [];

  console.log(`[Rollup Config] Found templates: ${templates.join(', ')}`);

  templates.forEach((template) => {
    // 处理组件/主应用文件
    const componentEntries = getComponentEntries(template);
    componentEntries.forEach((compEntry) => {
      const aliases = generateAliases(template);

      configs.push({
        input: compEntry.path,
        output: {
          format: 'iife',
          file: compEntry.output,
        },
        plugins: [
          alias({ entries: aliases }),
          nodeResolve(),
          less({ output: false }),
          commonjs(),
          terser(),
          babel({
            exclude: 'node_modules/**',
          }),
        ],
      });

      console.log(`[Rollup Config] Added ${compEntry.name} bundle for ${template}: ${compEntry.path} -> ${compEntry.output}`);
    });

    // 处理页面文件
    const pageEntries = getPageEntries(template);
    console.log(`[Rollup Config] Template "${template}" found ${pageEntries.length} pages: ${pageEntries.map((p) => p.name).join(', ')}`);

    pageEntries.forEach((pageEntry) => {
      const aliases = generateAliases(template);

      // 为特定页面添加专用别名
      const pageAliases = [...aliases];
      if (pageEntry.name === 'singlePage') {
        pageAliases.push({
          find: '@singlePage',
          replacement: path.resolve(__dirname, `../src/theme/${template}/lib/page/singlePage`),
        });
      } else if (pageEntry.name === 'codPage') {
        pageAliases.push({
          find: '@codPage',
          replacement: path.resolve(__dirname, `../src/theme/${template}/lib/page/codPage`),
        });
      }


      configs.push({
        input: pageEntry.path,
        external: ['path', 'fs', 'stream', 'module'],
        output: {
          format: 'iife',
          file: pageEntry.output,
          banner: () => {
            if (pageEntry.output.includes('public.js')) {
              return fs.readFileSync(path.resolve(__dirname, '../scripts/vendor.js'), 'utf8');
            }
            return '';
          },
        },
        plugins: [
          alias({ entries: pageAliases }),
          nodeResolve(),
          less({ output: false }),
          commonjs(),
          terser(),
          babel({
            exclude: 'node_modules/**',
          }),
        ],
      });

      console.log(`[Rollup Config] Added page bundle: ${pageEntry.path} -> ${pageEntry.output}`);
    });
  });

  console.log(`[Rollup Config] Total configurations: ${configs.length}`);
  return configs;
}

module.exports = generateConfig();
